import os
import win32com.client as win32
from docx2pdf import convert as docx_to_pdf
import pandas as pd
#word和excel转换成pdf
# 电脑需要下载安装libpreoffice组件  https://www.libreoffice.org/download/download-libreoffice/
def convert_docx_to_pdf(docx_file_path, pdf_file_path):
    try:
        docx_to_pdf(docx_file_path, pdf_file_path)
        print(f"转换成功: {docx_file_path} -> {pdf_file_path}")
    except Exception as e:
        print(f"转换失败: {docx_file_path}, 错误信息: {str(e)}")

def convert_excel_to_pdf(excel_file_path, pdf_file_path):
    try:
        excel = win32.gencache.EnsureDispatch('Excel.Application')
        workbook = excel.Workbooks.Open(excel_file_path)
        workbook.ExportAsFixedFormat(0, pdf_file_path)  # 0 = xlTypePDF
        workbook.Close(False)
        excel.Quit()
        print(f"转换成功: {excel_file_path} -> {pdf_file_path}")
    except Exception as e:
        print(f"转换失败: {excel_file_path}, 错误信息: {str(e)}")

def batch_convert_files(directory, output_directory):
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    for file_name in os.listdir(directory):
        file_path = os.path.join(directory, file_name)
        if file_name.endswith('.docx'):
            pdf_file_path = os.path.join(output_directory, os.path.splitext(file_name)[0] + '.pdf')
            convert_docx_to_pdf(file_path, pdf_file_path)
        elif file_name.endswith(('.xls', '.xlsx')):
            pdf_file_path = os.path.join(output_directory, os.path.splitext(file_name)[0] + '.pdf')
            convert_excel_to_pdf(file_path, pdf_file_path)

if __name__ == "__main__":
    input_directory = "F:\\knowledge2"  # 输入文件夹路径
    output_directory = "F:\\knowledge2\\pdf"  # 输出文件夹路径
    batch_convert_files(input_directory, output_directory)
